#include "mystdio.h"
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

static MyFile *createFile(int fd, int flag)
{
  //创建一个文件对象
  MyFile *temp = (MyFile*)malloc(sizeof(MyFile));
  temp->fileno = fd;
  temp->flag = flag;
  temp->bufflen = 0;
  temp->flush_method = LINE_FLUSH;

  return temp;
}

MyFile *MyFopen(const char *path, const char *mode)
{
  int fd = -1;
  int flag = 0;

  //判断打开方式并打开
  if(strcmp(mode, "r") == 0)
  {
    flag = O_RDONLY;
    fd = open(path, flag);
  }
  else if(strcmp(mode, "w") == 0)
  {
    flag = O_CREAT | O_WRONLY | O_TRUNC;
    fd = open(path, flag, 0666);
  }
  else if(strcmp(mode, "a") == 0)
  {
    flag = O_CREAT | O_WRONLY | O_APPEND;
    fd = open(path, flag, 0666);
  } 
  
  if(fd < 0) return NULL;
  return createFile(fd, flag);

}
void MyFclose(MyFile *file)
{
  if(file == NULL ||file->fileno < 0) return;
  MyFflush(file);
  close(file->fileno);
  free(file);
}
int MyFwrite(MyFile *file, const void *str, int len)
{
  //写入文件对象缓冲区
  mempcpy(file->outbuff+file->bufflen, str, len);
  file->bufflen+=len;

  //判断是否要刷新
  int FlushMethod = file->flush_method;
  if(FlushMethod == NONE_FLUSH)
  {
    MyFflush(file);
  }
  else if((FlushMethod == LINE_FLUSH) && (file->outbuff[file->bufflen-1] == '\n' ))
  {
    MyFflush(file);
  }//行刷新
  else if((FlushMethod == FULL_FLUSH) && (file->bufflen == MAX_LEN))
  {
    MyFflush(file);
  }//全刷新

  return len;
}
void MyFflush(MyFile *file)
{
  if(file->bufflen > 0)
  {
    write(file->fileno, file->outbuff, file->bufflen);
    fsync(file->fileno);
    file->bufflen = 0;
  } 
}

